package consumer

import (
	sqlc "bp/db/sqlc"
	nsqMall "bp/internal/service/com/nsqMall"
	"bp/internal/util"
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"github.com/nsqio/go-nsq"
)

func (s *BizCancelConsumer) HandleMessage(m *nsq.Message) (err error) {
	ctx := context.Background()
	mPtr := &nsqMall.BizCancelNotification{}
	if err = json.NewDecoder(bytes.NewReader(m.Body)).Decode(mPtr); err != nil {
		err = fmt.Errorf("无法解析信息[BizCancelNotification]: %s", err.Error())
		return
	}
	messageBytes, err := json.Marshal(mPtr)
	if err != nil {
		return
	}
	notifySn := util.Md5WithoutDash(messageBytes)
	// 独立事务
	nsqSubPtr, err := s.entityHub.NsqService.UpsertNsqSub(ctx, s.dao.Q, s.topic, notifySn, messageBytes)
	if err != nil {
		return
	}
	if nsqSubPtr.IsHandleSuccess {
		// 消息已经handler,被补偿处理
		return
	}
	nsqSubID := nsqSubPtr.ID
	defer s.failover.HandleNsqSubFail(nsqSubID, &err)
	err = s.dao.NewTxRunner().SqlcExecTx(ctx, func(q *sqlc.Queries) (err error) {
		_, err = s.entityHub.NsqService.GetNsqSubPtrWithLock(ctx, q, nsqSubID)
		if err != nil {
			return
		}
		err = s.comHub.NsqMallService.HandleBizCancel(ctx, q, mPtr)
		if err != nil {
			return
		}
		err = s.entityHub.NsqService.MarkNsqSubHandleSuccess(ctx, q, nsqSubID)
		if err != nil {
			return
		}
		s.slog.Infof("nsq--外部交易(%s) HandleBizCancel ok", mPtr.OutTransNo)
		return
	})
	if err != nil {
		return
	}

	return
}
